import styles from './index.less';
import { Button, Select, Input, message, DatePicker, Form, Radio, Checkbox, Spin } from 'antd';
import {
  CFormItem,
  QQ,
  CnPriceBook,
  CnPriceDate,
  CnPriceSpike,
  CnOldTBringNew,
  CnGifts,
  Inputs,
} from '@/pages/pc/components/form';
import Card from '../card';
import { DraggerUpload, InnerUpload } from '@/pages/pc/components/Upload';
import { Tinymce } from '@/pages/pc/components';
import { allGet, allPost } from '@/services/pc';
import React, { FC, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { isVideo, formatObjToAntList, isImg, getBase64 } from '@/utils';
import VideoPlayerModal from '@/pages/pc/components/VideoPlayer';
import ProcessBarUpload from '@/pages/pc/components/Upload/ProcessBarUpload';
import { useHistory, useModel } from 'umi';
import moment from 'moment';
import downloadIcon from '@/assets/pc/images/download-icon.png';
import editAv1 from '@/assets/pc/images/edit-1.png';
import editAv2 from '@/assets/pc/images/edit-2.png';
import classNames from 'classnames';
import ReactHtmlParser from 'react-html-parser';
import { apiUrl } from '@/common/const';

export type ActionRefType = {
  onSubmit: (postsubmit: string) => Record<string, any>;
  validateFields: () => Promise<any>;
};

export interface EditInstance {
  getData: (postsubmit: string) => Promise<any>;
  validateTinymce: () => Promise<any>;
  validateFields: () => Promise<any>;
}
const Index = React.forwardRef<EditInstance, any>((props, ref) => {
  const initialValues = useMemo(
    () => ({
      commoncoupon: false,
      secskills: false,
      rewards: '',
      gifts: [{}],
      invitebuy: false,
      sharecoupon: false,
      students: false,
      cashback: [undefined],
    }),
    [],
  );
  /**
   * 上传用到的参数
   */

  const editRef = useRef();
  const { userInfo } = useModel('user');

  const [config, setConfig] = useState<any>({});
  const [loading, setLoading] = useState(true);
  //宣传视频的值
  const promotionalVideoRef = useRef<any>([]);
  // 上传课程详情图片/视频的值
  const classDetailPicVideoRef = useRef<any[]>([]);
  const [formRef] = Form.useForm();
  const [defaultMessage, setDefaultMessage] = useState<string>();

  // 预售时间是否可输入
  const [secskillpriceDisabled, setSecskillpriceDisabled] = useState(true);
  const [bookPriceDisabled, setBookPriceDisabled] = useState(true);
  const [teacherList, setTeacherList] = useState([]);
  const [giftsDisabled, setGiftsDisabled] = useState(true);

  // 讲师列表
  const getTeacherList = async () => {
    const response = await allGet({
      params: { mod: 'teacher', do: 'list', version: 'pc1.0', page: 1, perpage: 9999 },
    });
    if (response.code === 0) {
      setTeacherList(response.data.list);
    }
  };

  useEffect(() => {
    init();
  }, [teacherList, userInfo?.uid]);

  // 设置CG券/实物的初始值
  const setGiftsinitialValues = (config) => {
    const gifts = config?.data?.files?.gift;

    // 不是编辑
    if (!classid) {
      const course = config?.data?.coursetmp?.data || {};
      const rewards = course?.rewards;
      console.log(rewards, 'rewards');
      formRef.setFieldsValue({
        isRewards: course?.isRewards === 'true',
      });
      setGiftsDisabled(course?.isRewards !== 'true');
      if (rewards === 'credit') {
        formRef.setFieldsValue({
          gifts: [{ quota: course.creditamount, limit: course.creditlimit }],
          rewards: 'credit',
        });
      }

      if (rewards === 'gift' && course.gifts?.length > 0) {
        const giftsValues = course.gifts || [];
        const giftsMaps = {};
        gifts?.forEach((item) => {
          giftsMaps[item.aid] = item;
        });
        const newGifts = giftsValues
          .map((item) => {
            const file = giftsMaps[item.aid];
            if (!file) return;
            return {
              ...file,
              url: file.attachment,
              name: file.filename,
              uid: file.aid,
              status: 'done',
              limit: item.limit,
            };
          })
          .filter((item) => item);
        formRef.setFieldsValue({
          gifts: newGifts,
          rewards: 'gift',
        });
      }
      return;
    } else {
      const rewards = config?.data?.course?.rewards;

      if (rewards?.type === 'credit') {
        formRef.setFieldsValue({
          gifts: [{ quota: rewards.amount, limit: rewards.limit }],
          rewards: 'credit',
          isRewards: true,
        });
        setGiftsDisabled(false);
      }
      if (rewards?.type === 'gift' && rewards?.gifts?.length > 0) {
        const giftsValues = rewards?.gifts || [];
        const giftsMaps = {};

        gifts?.forEach((item) => {
          giftsMaps[item.aid] = item;
        });
        const newGifts = giftsValues
          .map((item) => {
            const file = giftsMaps[item.aid] || {};
            if (!file) return;
            return {
              ...item,
              url: file.name,
              name: file.name,
              uid: file.aid,
              status: 'done',
              limit: item.limit,
            };
          })
          .filter((item) => item);
        formRef.setFieldsValue({
          gifts: newGifts,
          rewards: 'gift',
          isRewards: true,
        });
        setGiftsDisabled(false);
      }
    }
  };

  // 有课程id的设置默认值
  const setInitialValuesByClassid = (config) => {
    const course = config?.data?.course;
    if (!course) return;
    setDefaultMessage(course.message);
    editRef.current?.setValue?.(course.message);
    if (Number(course.bookprice) >= 0) {
      setSecskillpriceDisabled(true);
      setBookPriceDisabled(false);
    } else if (course.secskills) {
      setSecskillpriceDisabled(false);
      setBookPriceDisabled(true);
    } else {
      setSecskillpriceDisabled(true);
      setBookPriceDisabled(true);
    }
    console.log('教师名称', config?.data?.course?.uid, userInfo.uid);
    //  教师名称
    if (config?.data?.course?.uid === userInfo.uid) {
      setTeacherName(userInfo.username);
      setUid(userInfo.uid);
      setAvatar(userInfo.avatar);
      teacherNameRef.current = userInfo?.username
        ? {
            label: userInfo?.username,
            value: userInfo?.uid,
            title: userInfo.avatar,
          }
        : undefined;
    } else {
      const tId = config?.data?.course?.uid;
      const t: any = teacherList.filter((item: any) => item.uid === tId)?.[0];
      setTeacherName(t?.username);
      setUid(t?.uid);
      setAvatar(t?.photo);
      teacherNameRef.current = t?.username
        ? {
            label: t?.username,
            value: t?.uid,
            title: t?.photo,
          }
        : undefined;
    }
    setHeadmasters(course?.headmasters?.filter?.((item) => !!item) || []);
    // 秒杀，not json
    // const secskills = course.secskills ? JSON.parse(course.secskills) : {};
    // console.log(secskills);
    formRef.setFieldsValue({
      name: course.name,
      message: course.message,
      type: course.type !== undefined && course.type != null ? String(course.type) : undefined,
      price: course.price,
      bookprice:
        Number(course.bookprice) >= 0
          ? {
              price: course.bookprice,
              date:
                course?.bookdead && moment(course?.bookdead, 'X').isValid()
                  ? moment(course?.bookdead, 'X')
                  : undefined,
            }
          : undefined,
      isBook: Number(course.bookprice) >= 0,
      fqipay:
        course.fqipay === undefined || course.fqipay === null ? undefined : String(course.fqipay),
      cid: course.cid !== undefined && course.cid != null ? String(course.cid) : undefined,
      services: course?.services ? course?.services?.split?.(',') : [],
      softids: course?.softids || [],
      teacherqq: {
        qq: course?.qqqun,
        wx: course?.weixinteacher,
      },
      // contractMethodType: course?.teacherqq ? 'qq' : 'wx',
      // contractMethod: course.weixinteacher || course.teacherqq,
      viewip: course.viewip,
      commoncoupon: course?.coupons?.commoncouponamount > 0 ? true : false,
      commoncouponamount: {
        price: course?.coupons?.commoncouponamount > 0 ? course?.coupons?.commoncouponamount : '',
        date:
          course?.coupons?.commoncoupondead &&
          moment(course?.coupons?.commoncoupondead, 'X').isValid()
            ? moment(course?.coupons?.commoncoupondead, 'X')
            : undefined,
      },
      sharecoupon: course?.coupons?.sharecouponamount > 0 ? true : false,
      sharecouponamount: {
        price: course?.coupons?.sharecouponamount > 0 ? course?.coupons?.sharecouponamount : '',
        date:
          course?.coupons?.sharecoupondead &&
          moment(course?.coupons?.sharecoupondead, 'X').isValid()
            ? moment(course?.coupons?.sharecoupondead, 'X')
            : undefined,
      },
      students: course?.students?.studentreduce > 0 ? true : false,
      studentreduce: {
        price: course?.students?.studentreduce > 0 ? course?.students?.studentreduce : '',
        date:
          course?.students?.studentdead && moment(course?.students?.studentdead, 'X').isValid()
            ? moment(course?.students?.studentdead, 'X')
            : undefined,
      },
      secskills: course?.secskills?.secskillprice > 0,
      secskillprice: {
        price: course?.secskills?.secskillprice > 0 ? course?.secskills?.secskillprice : undefined,
        count: course?.secskills?.secskilllimit > 0 ? course?.secskills?.secskilllimit : undefined,
        date:
          course?.secskills?.secskillstart &&
          course?.secskills?.secskilldead &&
          moment(course?.secskills?.secskillstart, 'X').isValid() &&
          moment(course?.secskills?.secskilldead, 'X').isValid()
            ? [
                moment(course?.secskills?.secskillstart, 'X'),
                moment(course?.secskills?.secskilldead, 'X'),
              ]
            : undefined,
      },
      invitebuy:
        Array.isArray(course?.invitebuys?.cashback) && course?.invitebuys?.cashback.length > 0,
      cashback: course?.invitebuys?.cashback || [],
      reduce: Array.isArray(course?.invitebuys) ? undefined : course?.invitebuys?.reduce,
      freeusers: course?.freeusers?.length > 0 ? course?.freeusers?.split('\n') : undefined,
      title: course?.title,
      keywords: course?.keywords,
      description: course?.description,
    });
    // console.log(course, 'course');
  };

  // 没id的设置默认值
  const setInitialValuesByNoClassid = (config) => {
    const course = config?.data?.coursetmp?.data;
    if (!course) return;
    setDefaultMessage(course.message);
    editRef.current?.setValue?.(course.message);
    // 预售时间是否可编辑
    if (course.bookprice) {
      setSecskillpriceDisabled(true);
      setBookPriceDisabled(false);
    } else if (course.secskills) {
      setSecskillpriceDisabled(false);
      setBookPriceDisabled(true);
    } else {
      setSecskillpriceDisabled(true);
      setBookPriceDisabled(true);
    }
    //  教师名称
    console.log('教师名称', config?.data?.coursetmp?.uid, userInfo.uid);
    if (config?.data?.coursetmp?.uid === userInfo.uid) {
      setTeacherName(userInfo.username);
      setUid(userInfo.uid);
      setAvatar(userInfo.avatar);
      teacherNameRef.current = userInfo?.username
        ? {
            label: userInfo?.username,
            value: userInfo?.uid,
            title: userInfo.avatar,
          }
        : undefined;
    } else {
      const tId = config?.data?.coursetmp?.uid ?? userInfo.uid;
      const t: any = teacherList.filter((item: any) => item.uid === tId)?.[0];
      setTeacherName(t?.username);
      setUid(t?.uid);
      setAvatar(t?.photo);
      teacherNameRef.current = t?.username
        ? {
            label: t?.username,
            value: t?.uid,
            title: t?.photo,
          }
        : undefined;
    }

    setHeadmasters(course?.headmasters?.length > 0 ? course?.headmasters?.split?.('\n') : []);
    // 秒杀，not json
    // const secskills = course.secskills ? JSON.parse(course.secskills) : {};
    // console.log(secskills);
    formRef.setFieldsValue({
      message: course.message,
      name: course.name,
      type: course.type,
      price: course.price,
      bookprice: course.bookprice
        ? {
            price: course.bookprice,
            date:
              course?.bookdead && moment(course?.bookdead, 'YYYY-MM-DD').isValid()
                ? moment(course?.bookdead, 'YYYY-MM-DD')
                : undefined,
          }
        : undefined,
      isBook: Boolean(course.bookprice),
      fqipay: course.fqipay,
      cid: course.cid,
      services: course?.services?.split?.(',') || [],
      softids: course?.softids?.length > 0 ? course?.softids.split(',') : [],
      teacherqq: {
        qq: course?.qqqun,
        wx: course?.weixinteacher,
      },
      // contractMethodType: course?.teacherqq ? 'qq' : 'wx',
      // contractMethod: course.weixinteacher || course.teacherqq,
      viewip: course.viewip,
      bookdead:
        course.bookdead && moment(course.bookdead).isValid() ? moment(course.bookdead) : undefined,
      commoncoupon: course.commoncoupon == 1,
      commoncouponamount: {
        price: course?.commoncouponamount > 0 ? course?.commoncouponamount : '',
        date:
          course?.commoncoupondead && moment(course?.commoncoupondead).isValid()
            ? moment(course?.commoncoupondead)
            : undefined,
      },
      sharecoupon: course?.sharecoupon == 1,
      sharecouponamount: {
        price: course?.sharecouponamount > 0 ? course?.sharecouponamount : '',
        date:
          course?.sharecoupondead && moment(course?.sharecoupondead).isValid()
            ? moment(course?.sharecoupondead)
            : undefined,
      },
      students: course.students == 1,
      studentreduce: {
        price: course?.studentreduce > 0 ? course?.studentreduce : '',
        date:
          course?.studentdead && moment(course?.studentdead).isValid()
            ? moment(course?.studentdead)
            : undefined,
      },
      secskills: course.secskills == 1,
      secskillprice: {
        price: course?.secskillprice > 0 ? course?.secskillprice : undefined,
        count: course?.secskilllimit > 0 ? course?.secskilllimit : undefined,
        date:
          course?.secskillstart &&
          course?.secskilldead &&
          moment(course?.secskillstart).isValid() &&
          moment(course?.secskilldead).isValid()
            ? [moment(course?.secskillstart), moment(course?.secskilldead)]
            : undefined,
      },
      invitebuy: course?.invitebuy == 1,
      cashback: course?.cashback || [],
      reduce: course?.reduce,
      freeusers: course?.freeusers?.length > 0 ? course?.freeusers?.split('\n') : undefined,
      title: course?.title,
      keywords: course?.keywords,
      description: course?.description,
    });
    console.log(course, 'course');
  };
  const setInitialValues = (config) => {
    // 发布过的有课程id的
    // 回填表单内容
    if (classid) {
      setInitialValuesByClassid(config);
      classDetailPicVideoRef.current =
        config?.data?.course?.messageindex
          ?.filter?.((item) => item)
          ?.map?.((item) => {
            const url = item.videoid ? item.attachment : item.pic;
            return {
              ...item,
              url,
              name: item.filename,
              uid: item.aid,
              videoId: item.videoid,
              status: 'done',
            };
          }) || [];
      //return;
    } else {
      setInitialValuesByNoClassid(config);
      classDetailPicVideoRef.current =
        config?.data?.coursetmp?.data?.messageindex
          ?.filter?.((item) => item)
          ?.map?.((item) => {
            const url = item.videoid ? item.attachment : item.pic;
            return {
              ...item,
              url,
              name: item.filename,
              uid: item.aid,
              videoId: item.videoid,
              status: 'done',
            };
          }) || [];
    }

    /**
     * 回填各种图片/视频附件内容
     */
    const spread = config?.data?.files?.spread || [];
    const promotionalVideoObj = spread[spread.length - 1] || {};
    promotionalVideoRef.current =
      spread.length > 0
        ? [
            {
              ...promotionalVideoObj,
              url: promotionalVideoObj.attachment,
              name: promotionalVideoObj.filename,
              uid: promotionalVideoObj.aid,
              videoId: promotionalVideoObj.videoid,
              status: 'done',
            },
          ]
        : [];

    // 上传课程详情图片/视频的值

    // 封面图
    const covers = config?.data?.files?.cover || [];
    if (Array.isArray(covers) && covers.length > 0) {
      setCover({
        ...covers[0],
        url: covers[0].pic,
      });
    }

    setGiftsinitialValues(config);
  };

  /**
   * 获取课程详情数据
   */
  const { classid = 0 } = (useHistory().location as any)?.query;
  const init = async () => {
    setLoading(true);
    /**
     * testid 285
     */
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid /* classid */ },
    }).catch();
    const config = response?.data || {};
    config.types = formatObjToAntList(config.types);
    config.fqipays = formatObjToAntList(config.fqipays);
    setConfig(response.data);
    setInitialValues(response);
    setLoading(false);
  };
  useEffect(() => {
    getTeacherList();
  }, []);

  const uploadVideo2PhpTimer = useRef<any>();
  // 上传阿里云视频成功，视频要单独处理
  const handleUploadSuccess = async (file, field) => {
    if (isVideo(file.name)) {
      file.videoId = file?.response?.videoId;
      const response = await allGet({
        params: {
          version: 'pc1.0',
          mod: 'video',
          do: 'aliyun',
          action: 'upload',
          type: 'course',
          field,
          aid: file.aid || 0,
          filename: file.name,
          videoid: file.videoId,
        },
      });
      if (!response.success) {
        clearTimeout(uploadVideo2PhpTimer.current);
        return;
      }
      file.aid = response?.data?.attachid;
      if (response.success && response.data.attachment) {
        clearTimeout(uploadVideo2PhpTimer.current);
        file.attachment = response.data.attachment;
        if (field === 'spread') {
          promotionalVideoRef.current = [
            {
              ...file,
            },
          ];
        }
        if (field === 'message') {
          classDetailPicVideoRef.current.push({ ...file });
        }
      } else {
        setTimeout(() => {
          handleUploadSuccess(file, field);
        }, 500);
      }
    } else {
      if (field === 'message') {
        classDetailPicVideoRef.current.push({ ...file });
      }
    }
  };
  // 课程详情视频点击查看
  const handlePreview = async (file) => {
    if (!file.url) {
      /**
       * @tudo
       * 参数得成你需要的
       */
      const response = await allGet({
        params: {
          version: 'pc1.0',
          mod: 'video',
          do: 'aliyun',
          action: 'upload',
          type: 'teacher',
          aid: file.aid,
          videoid: file.videoId,
        },
      });
      if (!response?.data?.attachment) {
        return message.info('视频上传中，请稍后再试');
      }
      file.url = response?.data?.attachment;
    }
    VideoPlayerModal.showList({
      data: [
        {
          url: file.url,
        },
      ],
    });
  };
  // 删除上传课程详情视频/图片
  const handleRemove = async (file, index) => {
    if (file.status === 'error') return true;
    const reponse = await allGet({
      params: { mod: 'attachment', do: 'delete', aid: file.aid, version: 'pc1.0' },
    });
    if (reponse.success) {
      // classDetailPicVideoRef.current.splice(index, 1);
      return true;
    }
    return false;
  };
  // 上传课程详情图片的携带参数
  const uploadPayload = {
    mod: 'swfupload',
    ac: 'course',
    field: 'message',
    version: 'pc1.0',
    uid: config?.swfconfig?.uid,
    hash: config?.swfconfig?.hash,
    /**
     * 编辑的时候需要传入classid
     */
    classid,
  };

  // 上传增送实物的图片参数
  const uploadGiftPayload = {
    mod: 'swfupload',
    ac: 'course',
    field: 'gift',
    version: 'pc1.0',
    uid: config?.swfconfig?.uid,
    hash: config?.swfconfig?.hash,
    /**
     * 编辑的时候需要传入classid
     */
    classid,
  };
  // 阿里云token
  const getAliyunAuth = async (data = {} as any) => {
    const response = await allGet({
      params: {
        mod: 'video',
        do: 'aliyun',
        version: 'pc1.0',
        action: 'CreateUploadVideo',
        CateId: '1000422147',
        ...data,
      },
    });
    return response?.data || {};
  };
  // 刷新阿里云token
  const refreshAliyunAuth = async (data = {}) => {
    const response = await allGet({
      params: {
        mod: 'video',
        do: 'aliyun',
        version: 'pc1.0',
        action: 'RefreshUploadVideo',
        ...data,
      },
    });
    return response?.data || {};
  };

  const handlePromotionalVideoBeforeUpload = async (file) => {
    if (!isVideo(file.name)) {
      message.error('视频仅支持 avi/mp4/mov 格式');
      return false;
    }
    return true;
  };

  const rewards = Form.useWatch('rewards', formRef);
  const isRewards = Form.useWatch('isRewards', formRef);

  const getFormValue = () => {
    formRef.validateFields();
    console.log(formRef.getFieldsValue(), 'form values');
  };

  const handleRewardsChange = (e) => {
    const gifts = formRef.getFieldValue('gifts');
    formRef.resetFields(['gifts']);
    // 切换到cg券，要循环删除实物图片
    if (e.target.value === 'credit') {
      gifts?.forEach?.((item) => {
        if (item.aid) {
          allGet({
            params: { mod: 'attachment', do: 'delete', aid: item.aid, version: 'pc1.0' },
          });
        }
      });
    }
  };

  const [coverLoading, setCoverLoading] = useState(false);

  // 上传封面
  const [cover, setCover] = useState<any>();
  const uploadCoverProps = {
    action: apiUrl,
    name: 'Filedata',
    multiple: false,
    data: {
      mod: 'swfupload',
      ac: 'course',
      field: 'cover',
      version: 'pc1.0',
      uid: config?.swfconfig?.uid,
      hash: config?.swfconfig?.hash,
      /**
       * 编辑的时候需要传入classid
       */
      classid,
    },
    beforeUpload: async (file, fileList) => {
      const isimg = isImg(file.name);
      // 格式不符合
      if (!isimg) {
        message.error('图片仅支持 jpg/png/gif/webp 格式');
        return false;
      }
      setCoverLoading(true);
      return true;
    },
    onSuccess: async (_, file) => {
      const { response, ...item } = file;
      const url = await getBase64(file);
      const data = { ...item, ...(response.data || {}), url };
      setCover(data);
    },
    onChange: async (_, file) => {
      if (file.status === 'done' || file.status === 'error') {
        setCoverLoading(false);
      }
    },
  };

  const onSubmit = async (postsubmit) => {
    let isERR = false;
    const values = await formRef.validateFields().catch((err) => {
      formRef.scrollToField(err.errorFields?.[0]?.name?.[0]);
      throw new Error('校验失败');
      isERR = true;
    });
    if (isERR) return;
    const message = editRef.current?.getValue();
    const {
      price,
      fqipay,
      services,
      softids,
      contractMethodType,
      contractMethod,
      bookdead,
      freeusers,
      // checked -->  commoncoupon,students,sharecoupon,secskills,isRewards,invitebuy,isfreeusers
      commoncoupon, // 使用通用优惠券
      sharecoupon, // 使用分享优惠券;1:使用;0：不使用
      invitebuy, // 老带新用户购买
      secskills, // 秒杀
      students, // 老学员优惠
      commoncouponamount,
      studentreduce,
      sharecouponamount,
      secskillprice, // 秒杀详情
      gifts,
      cashback,
      bookprice,
      teacherqq,
      ...val
    } = values;
    const data = {
      classid,
      version: 'pc1.0',
      mod: 'course',
      do: 'post',
      postsubmit,
      username: teacherName,
      price: price,
      fqipay: fqipay,
      services: services?.join(','),
      softids: softids?.join(','),
      cashback: cashback?.filter?.((item) => item),
      qqqun: teacherqq?.qq,
      weixinteacher: teacherqq?.wx,
      bookdead: bookprice?.date?.format('YYYY-MM-DD'),
      bookprice: bookprice?.price,
      freeusers: freeusers?.length > 0 ? freeusers?.join('\n') : undefined,
      headmasters: headmasters?.length > 0 ? headmasters?.join('\n') : undefined,
      pic: cover?.attachment, // 封面 aid | attachment
      video: promotionalVideoRef.current?.[0]?.attachment,
      attach_ids: [
        cover?.aid,
        promotionalVideoRef.current?.[0]?.aid,
        ...classDetailPicVideoRef.current?.map(({ aid }) => aid),
      ].filter((item) => !!item),
      // 这里注释掉，因为右边tab上传课时视频还有类似的附件id要加入attach_ids里，转成逗号分隔的就放到父级提交的时候去处理
      // .join(','),

      messageindex: classDetailPicVideoRef.current?.map(({ aid }) => aid).join(','),
      commoncoupon: Number(commoncoupon),
      sharecoupon: Number(sharecoupon),
      invitebuy: Number(invitebuy),
      secskills: Number(secskills),
      students: Number(students),
      commoncouponamount: commoncouponamount?.price,
      commoncoupondead: commoncouponamount?.date?.format('YYYY-MM-DD'),
      studentreduce: studentreduce?.price,
      studentdead: studentreduce?.date?.format('YYYY-MM-DD'),
      sharecouponamount: sharecouponamount?.price,
      sharecoupondead: sharecouponamount?.date?.format('YYYY-MM-DD'),
      secskillprice: secskillprice?.price,
      secskilllimit: secskillprice?.count,
      secskillstart: secskillprice?.date?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
      secskilldead: secskillprice?.date?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
      uid,
      ...val,
      message,
    };

    if (rewards === 'credit') {
      //cg
      if (Array.isArray(gifts) && gifts?.length > 0) {
        data.creditamount = gifts[0].quota;
        data.creditlimit = gifts[0].limit;
      }
    } else {
      //实物
      // 转换jsonstringify
      if (Array.isArray(gifts) && gifts?.length > 0) {
        data.gifts = JSON.stringify(
          gifts
            .filter((item) => item.limit !== undefined)
            .map((item, index) => {
              if (item.aid) {
                // 顺便加入到attach_ids里
                data.attach_ids?.push?.(item.aid);
              }

              return { name: `礼物${index + 1}`, aid: item.aid, limit: item.limit };
            }),
        );
      }
    }

    return data;
  };
  // 助教
  const [headmasters, setHeadmasters] = useState([]);

  const [messageStatus, setMessageStatus] = useState(false);

  /**
   * 供父组件调用
   */
  useImperativeHandle(ref, () => ({
    getData: (postsubmit) => {
      return onSubmit(postsubmit);
    },
    validateFields: formRef.validateFields,
    validateTinymce: async () => {
      const message = editRef.current?.getValue();
      if (!message) {
        return false;
      }
      return true;
    },
  }));

  const [teacherName, setTeacherName] = useState('');
  const [uid, setUid] = useState();
  const [avatar, setAvatar] = useState(userInfo?.avatar);
  const teacherNameRef = useRef();
  const [editTeacherName, setEditTeacherName] = useState(false);
  return (
    <Spin spinning={loading}>
      <Form form={formRef} name="edit" initialValues={initialValues}>
        {/* <Affix offsetTop={200} style={{ position: 'absolute', right: 0 }}>
        <Button type="primary" onClick={getFormValue}>
          点我输出form的值
        </Button>
      </Affix> */}
        <div className={styles.container}>
          {/* 基本信息 */}
          <div className={styles['base-container']}>
            <div className={styles.left}>
              <div className={styles.teacherinfo}>
                <img loading="lazy" src={avatar} className={styles.avatar} />
                {!editTeacherName && <span className={styles.name}>{teacherName || '-'}</span>}
                {editTeacherName && (
                  <Select
                    defaultValue={uid}
                    size="small"
                    className={styles.editInput}
                    labelInValue
                    showSearch
                    onChange={(val) => {
                      teacherNameRef.current = val;
                    }}
                    filterOption={(input, option) => {
                      return (option?.children ?? '').toLowerCase().includes(input.toLowerCase());
                    }}
                    placeholder="请输入教师姓名"
                  >
                    {teacherList?.map((item: any) => (
                      <Select.Option key={item.uid} value={item.uid} title={item.photo}>
                        {item.username}
                      </Select.Option>
                    ))}
                  </Select>
                )}
                {!editTeacherName && (
                  <div className={styles.editPrimary} onClick={() => setEditTeacherName(true)}>
                    修改
                    <i className={styles.iconEdit} />
                  </div>
                )}
                {editTeacherName && (
                  <>
                    <div
                      className={styles.editPrimary}
                      onClick={() => {
                        console.log(teacherNameRef.current);
                        setTeacherName(teacherNameRef.current?.label);
                        setUid(teacherNameRef.current?.value);
                        setAvatar(teacherNameRef.current?.title);
                        setEditTeacherName(false);
                        // teacherNameRef.current = ''
                      }}
                    >
                      确定
                    </div>
                    <div
                      className={styles.editDefault}
                      onClick={() => {
                        teacherNameRef.current = undefined;
                        setEditTeacherName(false);
                      }}
                    >
                      取消
                    </div>
                  </>
                )}
              </div>

              <div className={styles.upload}>
                <Spin spinning={coverLoading}>
                  {cover?.url && (
                    <i
                      style={{ backgroundImage: `url(${cover.url})` }}
                      className={styles.coverimg}
                    />
                  )}
                  <div className={styles.img}>
                    <div className={styles['default-img']}>
                      <img
                        loading="lazy"
                        style={{ width: 43, height: 43 }}
                        src={downloadIcon}
                        alt=""
                      />
                      <span>支持 jpg/png/gif/webp 格式</span>
                      <span>推荐尺寸 800*656px</span>
                    </div>
                  </div>
                  <InnerUpload {...uploadCoverProps}>
                    <div className={styles.btn}>
                      <Button>上传封面 </Button>
                    </div>
                  </InnerUpload>
                </Spin>
              </div>
              {!loading && (
                <ProcessBarUpload
                  className={classNames(styles.promotionalVideo, 'promotionalVideo')}
                  prefix={<i className="icon-video-link" />}
                  tips="上传宣传视频（avi、mp4、mov）"
                  onBeforeUpload={handlePromotionalVideoBeforeUpload}
                  action={apiUrl}
                  onSuccess={(_, file) => handleUploadSuccess(file, 'spread')}
                  onRemove={() => (promotionalVideoRef.current = [])}
                  value={promotionalVideoRef.current}
                />
              )}
              <ul className={styles.ul}>
                <li>
                  <img loading="lazy" src={editAv1} alt="" />
                  <span>精致封面、高清的视频，详细趣味的讲解能吸引更多流量哦。</span>
                </li>
                <li>
                  <img loading="lazy" src={editAv2} alt="" />
                  <span>如遇到图片无法删除情况，请尝试清除浏览器缓存或换个浏览器操作。</span>
                </li>
              </ul>

              {/* <Select
                dropdownClassName="cn-select-dropdown-container"
                className="black-select"
                mode="tags"
                value={headmasters}
                placeholder="助教，回车确定"
                onChange={(value) => setHeadmasters(value)}
              /> */}
            </div>
            <div className={styles.right}>
              <h3>基本信息</h3>
              <div className={styles['right-content']}>
                <CFormItem
                  label="课程标题："
                  name="name"
                  rules={[{ required: true, message: '请输入' }]}
                >
                  <Input placeholder="请输入" />
                </CFormItem>
                <CFormItem
                  label="课程类型："
                  name="type"
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select
                    placeholder="请选择"
                    dropdownClassName="cn-select-dropdown-container"
                    onChange={(type) => {
                      // console.log(type);
                      setSecskillpriceDisabled(Number(type) !== 8);
                      formRef.setFieldValue('bookdead', undefined);
                      if (Number(type) === 8) {
                        formRef.setFieldValue('secskillprice', undefined);
                        formRef.setFieldValue('secskills', false);
                      }
                    }}
                  >
                    {config?.types?.map((item) => (
                      <Select.Option key={item.value} value={item.value}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </CFormItem>
                <CFormItem
                  renderLabel={() => (
                    <span>
                      课程售价：
                      <span style={{ color: '#fee500', fontSize: 12 }}>免费课程请填写“0”</span>
                    </span>
                  )}
                  name="price"
                  rules={[{ required: true, message: '请输入' }]}
                  getValueFromEvent={(evt) => {
                    if (evt.target.value == 0) return evt.target.value;
                    return evt.target.value?.replace(/^(0+)|[^\d]+/g, '');
                  }}
                >
                  <Input
                    type="number"
                    className="addon-yellow"
                    placeholder="填写课程售价"
                    addonAfter="¥"
                  />
                </CFormItem>

                <CFormItem
                  label="是否可以分期："
                  name="fqipay"
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select dropdownClassName="cn-select-dropdown-container" placeholder="选择分期">
                    {(config.fqipays || []).map(({ label, value }) => (
                      <Select.Option key={value}>{label}</Select.Option>
                    ))}
                  </Select>
                </CFormItem>
                {/* <CFormItem
                  label="预售截止时间："
                  name="bookdead"
                // rules={[{ required: true, message: '请输入' }]}
                >
                  <DatePicker
                    className="c-date-picker-container"
                    disabled={secskillpriceDisabled}
                    size="large"
                    placeholder=""
                    style={{ width: '100%', height: 44 }}
                  />
                </CFormItem> */}

                <CFormItem
                  label="课程分类："
                  name="cid"
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select
                    // mode="tags"
                    placeholder="请选择"
                    dropdownClassName="cn-select-dropdown-container"
                  >
                    {config?.categorys?.map((item) => (
                      <Select.Option key={item.cid} value={item.cid}>
                        {item.name}
                      </Select.Option>
                    ))}
                  </Select>
                </CFormItem>
                <CFormItem
                  name="teacherqq"
                  renderLabel={() => (
                    <div
                      style={{
                        display: 'inline-flex',
                        justifyContent: 'space-between',
                        width: 'calc(100% - 8px)',
                      }}
                    >
                      <span>学习交流群：</span>
                      <span
                        style={{
                          fontSize: 12,
                          fontFamily: 'PingFangSC-Regular, PingFang SC;',
                          display: 'inline-flex',
                          alignItems: 'center',
                          color: 'rgb(118, 136, 165)',
                        }}
                      >
                        微信群需要学员添加老师微信，邀请加入
                      </span>
                    </div>
                  )}
                >
                  <QQ />
                </CFormItem>
                {/* <CFormItem label="IP地址：" name="viewip">
                  <Input />
                </CFormItem> */}

                {/* <CFormItem
                  showRequired={false}
                  label="教室confkey："
                // rules={[{ required: true, message: '请输入' }]}
                >
                  <Input placeholder="该课程的在线直播教室的confkey。" disabled />
                </CFormItem> */}

                <CFormItem label="服务：" name="services">
                  <Select
                    mode="multiple"
                    showArrow
                    placeholder="请选择"
                    dropdownClassName="cn-select-dropdown-container"
                  >
                    {config?.services?.map((str) => (
                      <Select.Option key={str} value={str}>
                        {str}
                      </Select.Option>
                    ))}
                  </Select>
                </CFormItem>
                <CFormItem label="用到的软件：" name="softids">
                  <Select
                    showArrow
                    placeholder="请选择"
                    mode="multiple"
                    dropdownClassName="cn-select-dropdown-container"
                  >
                    {config?.softs?.map((item) => (
                      <Select.Option key={item.sid} value={item.sid}>
                        {item.subject}
                      </Select.Option>
                    ))}
                  </Select>
                </CFormItem>
              </div>
            </div>
          </div>

          <div style={{ borderRadius: 8, overflow: 'hidden', marginBottom: 30 }}>
            <Tinymce
              ref={editRef}
              action={apiUrl}
              payload={uploadPayload}
              name="Filedata"
              getAliyunAuth={getAliyunAuth}
              refreshAliyunAuth={refreshAliyunAuth}
            />
            {messageStatus && <div className="ant-form-item-explain-error">请输入课程详情</div>}
          </div>

          {false && (
            <div style={{ padding: 20, borderRadius: 8, background: '#2F5083' }}>
              <CFormItem name="message" className={styles.messageForm}>
                <Input.TextArea placeholder="作品说明" autoSize={{ minRows: 4, maxRows: 8 }} />
              </CFormItem>
            </div>
          )}

          {/* 上传课程详情 */}
          {false && (
            <div className={styles['upload-detail-container']}>
              {!loading && (
                <DraggerUpload
                  value={classDetailPicVideoRef.current}
                  size={20}
                  action={apiUrl}
                  payload={uploadPayload}
                  name="Filedata"
                  onSuccess={(_, file) => handleUploadSuccess(file, 'message')}
                  onSortEnd={(fileList) => (classDetailPicVideoRef.current = fileList)}
                  onPreview={handlePreview}
                  onRemove={handleRemove}
                  getAliyunAuth={getAliyunAuth}
                  refreshAliyunAuth={refreshAliyunAuth}
                  column={4}
                  tipsTitle="上传课程详情/视频"
                />
              )}
            </div>
          )}
          <Card
            title="优惠券设置"
            extra={<span className="text-yellow">优惠券只适合当前课程，且可以叠加使用</span>}
          >
            <div style={{ display: 'flex' }}>
              <CFormItem
                style={{ flex: 1, marginRight: 32 }}
                labelClassName="font-size-16"
                name="commoncouponamount"
                showRequired={false}
                rules={[
                  {
                    validator(_, value, callback) {
                      if (formRef.getFieldValue('commoncoupon') && (!value.price || !value.date)) {
                        callback('请完善优惠券信息');
                      } else {
                        callback();
                      }
                    },
                  },
                ]}
                renderLabel={() => (
                  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <Form.Item
                      name="commoncoupon"
                      valuePropName="checked"
                      style={{ marginBottom: 0, display: 'inline-flex' }}
                    >
                      <Checkbox>
                        <span>通用优惠券：</span>
                      </Checkbox>
                    </Form.Item>
                  </div>
                )}
              >
                <CnPriceDate inputPlaceholder="填写优惠券额度" />
              </CFormItem>
              <CFormItem
                style={{ flex: 1 }}
                labelClassName="font-size-16"
                name="studentreduce"
                showRequired={false}
                rules={[
                  {
                    validator(_, value, callback) {
                      if (formRef.getFieldValue('students') && (!value.price || !value.date)) {
                        callback('请完善优惠券信息');
                      } else {
                        callback();
                      }
                    },
                  },
                ]}
                renderLabel={() => (
                  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <Form.Item
                      name="students"
                      valuePropName="checked"
                      style={{ marginBottom: 0, display: 'inline-flex' }}
                    >
                      <Checkbox>
                        <span>老学员优惠：</span>
                      </Checkbox>
                    </Form.Item>
                  </div>
                )}
              >
                <CnPriceDate inputPlaceholder="填写固定额度" />
              </CFormItem>
            </div>
            <div style={{ display: 'flex' }}>
              <CFormItem
                style={{ flex: 1, marginRight: 32 }}
                labelClassName="font-size-16"
                name="sharecouponamount"
                showRequired={false}
                rules={[
                  {
                    validator(_, value, callback) {
                      if (formRef.getFieldValue('sharecoupon') && (!value.price || !value.date)) {
                        callback('请完善优惠券信息');
                      } else {
                        callback();
                      }
                    },
                  },
                ]}
                renderLabel={() => (
                  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <Form.Item
                      name="sharecoupon"
                      valuePropName="checked"
                      style={{ marginBottom: 0, display: 'inline-flex' }}
                    >
                      <Checkbox>
                        <span>分享得优惠券：</span>
                      </Checkbox>
                    </Form.Item>
                  </div>
                )}
              >
                <CnPriceDate inputPlaceholder="填写优惠券额度" />
              </CFormItem>
              <span style={{ flex: 1 }} />
            </div>
          </Card>
          <Card title="活动设置">
            <CFormItem
              showRequired={false}
              name="bookprice"
              labelClassName="font-size-16"
              renderLabel={() => (
                <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                  <Form.Item
                    valuePropName="checked"
                    name="isBook"
                    style={{ marginBottom: 0, display: 'inline-flex' }}
                  >
                    <Checkbox
                      onChange={(evt) => {
                        setBookPriceDisabled(!evt.target.checked);
                        if (evt.target.checked) {
                          if (formRef.getFieldValue('secskills')) {
                            formRef.setFieldsValue({ secskills: false });
                            formRef.setFieldsValue({ secskillprice: undefined });
                            setSecskillpriceDisabled(true);
                          }
                        } else {
                          formRef.setFieldsValue({ bookprice: undefined });
                        }
                      }}
                    >
                      <span>课程预售：</span>
                    </Checkbox>
                  </Form.Item>
                </div>
              )}
            >
              <CnPriceBook disabled={bookPriceDisabled} />
            </CFormItem>

            <CFormItem
              showRequired={false}
              name="secskillprice"
              labelClassName="font-size-16"
              renderLabel={() => (
                <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                  <Form.Item
                    valuePropName="checked"
                    name="secskills"
                    style={{ marginBottom: 0, display: 'inline-flex' }}
                  >
                    <Checkbox
                      onChange={(evt) => {
                        setSecskillpriceDisabled(!evt.target.checked);
                        if (evt.target.checked) {
                          if (formRef.getFieldValue('isBook')) {
                            formRef.setFieldsValue({ isBook: false });
                            formRef.setFieldsValue({ bookprice: undefined });
                            setBookPriceDisabled(true);
                          }
                        } else {
                          formRef.setFieldsValue({ secskillprice: undefined });
                        }
                      }}
                    >
                      <span>秒杀活动：</span>
                    </Checkbox>
                  </Form.Item>
                </div>
              )}
            >
              <CnPriceSpike disabled={secskillpriceDisabled} />
            </CFormItem>

            <div style={{ display: 'flex' }}>
              <CFormItem
                style={{ flex: 1, marginRight: 32 }}
                showRequired={false}
                labelClassName="font-size-16"
                name="gifts"
                renderLabel={() => (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Form.Item
                      name="isRewards"
                      valuePropName="checked"
                      style={{ marginBottom: 0, display: 'inline-flex', flex: 1 }}
                    >
                      <Checkbox
                        onChange={(evt) => {
                          setGiftsDisabled(!evt.target.checked);
                          if (!evt.target.checked) {
                            formRef.setFieldsValue({ gifts: [], rewards: undefined });
                          } else {
                            formRef.setFieldsValue({ rewards: 'credit' });
                          }
                        }}
                      >
                        <span>促销活动：</span>
                        <Form.Item
                          // initialValue="credit"
                          name="rewards"
                          style={{ marginBottom: 0, display: 'inline-flex' }}
                        >
                          <Radio.Group
                            disabled={giftsDisabled}
                            onChange={handleRewardsChange}
                            className="c-radio"
                          >
                            <Radio value="credit">赠送CG券</Radio>
                            <Radio value="gift">增送实物</Radio>
                          </Radio.Group>
                        </Form.Item>
                      </Checkbox>
                    </Form.Item>
                    <a
                      style={{
                        color: '#4DE7FF',
                        fontSize: 14,
                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                      }}
                      onClick={
                        rewards === 'gift'
                          ? () => {
                              const gifts = formRef.getFieldValue('gifts');
                              formRef.setFieldsValue({ gifts: [...(gifts ?? [{}]), {}] });
                            }
                          : undefined
                      }
                    >
                      {rewards === 'gift' ? '+增加' : '  '}
                    </a>
                  </div>
                )}
                //  rules={[{ required: true, message: '请输入' }]}
              >
                {rewards !== 'gift' ? (
                  <Inputs disabled={giftsDisabled} />
                ) : (
                  <CnGifts payload={uploadGiftPayload} />
                )}
              </CFormItem>
              <CFormItem
                style={{ flex: 1 }}
                showRequired={false}
                name="cashback"
                labelClassName="font-size-16"
                renderLabel={() => (
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      paddingRight: 4,
                    }}
                  >
                    <Form.Item
                      name="invitebuy"
                      valuePropName="checked"
                      style={{ marginBottom: 0, display: 'inline-flex' }}
                    >
                      <Checkbox>
                        <span>老带新用户购买：</span>
                        <span>
                          <span className="text-yellow">受邀用户可享团购价，额外优惠</span>
                          <Form.Item
                            name="reduce"
                            style={{ marginBottom: 0, display: 'inline-flex', marginLeft: 3 }}
                            getValueFromEvent={(evt) => {
                              return evt.target.value?.replace(/^(0+)|[^\d]+/g, '');
                            }}
                          >
                            <Input
                              style={{ width: 72 }}
                              className="addon-yellow"
                              size="small"
                              placeholder="额外优惠"
                              addonAfter="¥"
                              type="number"
                            />
                          </Form.Item>
                        </span>
                      </Checkbox>
                    </Form.Item>
                    <a
                      style={{
                        color: '#4DE7FF',
                        fontSize: 14,
                      }}
                      onClick={() => {
                        const cashback = formRef.getFieldValue('cashback');
                        formRef.setFieldsValue({
                          cashback: [...(cashback ?? [undefined]), undefined],
                        });
                        //formRef.setFieldValue('cashback', [...cashback, undefined]);
                      }}
                    >
                      +增加
                    </a>
                  </div>
                )}
              >
                <CnOldTBringNew />
              </CFormItem>
            </div>
          </Card>
          <Card title="其他设置">
            <CFormItem
              showRequired={false}
              labelClassName="font-size-16"
              name="freeusers"
              renderLabel={() => (
                <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                  <Form.Item
                    valuePropName="checked"
                    name="isfreeusers"
                    style={{ marginBottom: 0, display: 'inline-flex' }}
                  >
                    <span style={{ color: '#fff', fontSize: 16 }}>免费用户：</span>
                  </Form.Item>
                  <span style={{ color: '#7688a5', fontSize: 14 }}>
                    这儿设置的用户能免费查看该课程。
                  </span>
                </div>
              )}
            >
              <Select
                dropdownClassName="cn-select-dropdown-container"
                mode="tags"
                placeholder="按回车键Enter添加用户"
              />
            </CFormItem>
          </Card>
          <Card title="SEO字段">
            <div style={{ display: 'flex' }}>
              <CFormItem
                showRequired={false}
                style={{ flex: 1, marginRight: 32 }}
                labelClassName="font-size-16"
                name="title"
                renderLabel={() => (
                  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <span>SEO标题：</span>
                    <span style={{ color: '#7688a5', fontSize: 14 }}>
                      该课程网页的title，用于SEO
                    </span>
                  </div>
                )}
              >
                <Input placeholder="请输入标题" />
              </CFormItem>
              <CFormItem
                showRequired={false}
                style={{ flex: 1 }}
                labelClassName="font-size-16"
                name="keywords"
                renderLabel={() => (
                  <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <span>SEO关键词：</span>
                    <span style={{ color: '#7688a5', fontSize: 14 }}>
                      用于SEO，该课程网页的Keywords。不同词之间用“，”隔开
                    </span>
                  </div>
                )}
              >
                <Input placeholder="请输入关键词" />
              </CFormItem>
            </div>
            <CFormItem
              showRequired={false}
              labelClassName="font-size-16"
              name="description"
              renderLabel={() => (
                <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                  <span>SEO描述：</span>
                  <span style={{ color: '#7688a5', fontSize: 14 }}>
                    用于SEO，该课程网页的description
                  </span>
                </div>
              )}
            >
              <Input.TextArea autoSize={{ minRows: 5, maxRows: 5 }} placeholder="请输入描述" />
            </CFormItem>
          </Card>
        </div>
      </Form>
    </Spin>
  );
});

export default Index;
